package com.zwf.task;

/**
 * @Author zwf
 * @date 2024/2/18 12:34
 */

import com.zwf.entity.Orders;
import com.zwf.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类，定时处理订单状态
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")//每分钟触发一次
    //@Scheduled(cron = "0/5 * * * * ?")
    public void processTimeOutOrder(){
        log.info("定时处理超时订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);  //用于处理超时15分钟未支付的订单
        List<Orders> ordersList=orderMapper.findOutTimeByStatus(Orders.PENDING_PAYMENT,time);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单超时");
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        });
    }

    /**
     * 自动处理长时间派送中订单
     */
    @Scheduled(cron = "0 0 3 * * ?")//每天凌晨3点触发一次
    //@Scheduled(cron = "1/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("自动处理长时间派送中订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-180);  //用于处理上一天还在派送中的订单
        List<Orders> ordersList=orderMapper.findOutTimeByStatus(Orders.DELIVERY_IN_PROGRESS,time);
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });
    }
}
